package com.gitee.deament.tianyancha.core.gencode;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.template.engine.velocity.VelocityUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.gitee.deament.tianyancha.core.GenColumn;
import com.gitee.deament.tianyancha.core.GenDTOColumn;
import org.apache.velocity.VelocityContext;

import java.io.File;
import java.util.*;

/**
 * 生成dto
 *
 * @author deament
 */
public class GenDTO {
    /**
     * 基本的包路径（）
     */
    private static String modelName;


    public static void gen(String url) {
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray apiListJsonArray = jsonObject.getJSONObject("data").getJSONArray("items");
        if (apiListJsonArray.size() == 0) {
            System.out.println("没有接口");
            return;
        }
        Map<String, Object> contextMap = new HashMap<>(10);

        final ResourceBundle rb = ResourceBundle.getBundle("TianyanchaGen");
        for (String key : rb.keySet()) {
            String value = rb.getString(key);
            contextMap.put(key, value);

        }
        String[] excludeUrls = rb.getString("excludeUrl").split(",");
        for (int i = 0; i < apiListJsonArray.size(); i++) {
            JSONObject apiInfo = apiListJsonArray.getJSONObject(i);
            if (!apiInfo.getString("furl").equals("/services/open/hi/ic/2.0")) {
                //  continue;
            }
            boolean excludeThisUrl=false;
            for (String excludeUrl : excludeUrls) {
                if(apiInfo.getString("furl").equals(excludeUrl)){
                    //有问题的api文档跳过
                    excludeThisUrl=true;
                    break;
                }
            }
            if(excludeThisUrl){
                continue;
            }
            contextMap.put("tianyancha", apiInfo);
            String className = getClassName(apiInfo.getString("furl"));
            contextMap.put("className", className);
            modelName = className.toLowerCase();
            contextMap.put("parent", rb.getString("parent") + "." + modelName + ".dto");
            JSONObject returnParam = JSONObject.parseObject(apiInfo.getString("requestParam").replaceAll("↵", ""));
            if (returnParam == null) {
                continue;
            }
            List<GenDTOColumn> columns = new ArrayList<>();
           // System.out.println(JSONObject.toJSONString(returnParam, true));
            for (String key : returnParam.keySet()) {
                GenDTOColumn column = new GenDTOColumn();
                column.setType(returnParam.getJSONObject(key).getString("type"));
                if(column.getType()==null || column.getType().length()==0){
                    column.setType("String");
                }
                column.setType(GenUtil.captureName(column.getType()));
                column.setName(key);
                column.setAttrName(GenUtil.captureName(key));
                column.setRemark(returnParam.getJSONObject(key).getString("remark"));
                column.setRequire(returnParam.getJSONObject(key).getBoolean("require"));
                converNumber(column);
                columns.add(column);
            }
            contextMap.put("columns", columns);
            VelocityContext context = new VelocityContext(contextMap);
            File file = new File("src/main/resources/genCode/DTO.ftl");
            String gencontext = FileUtil.readUtf8String(file);
            String data = VelocityUtil.merge(gencontext, context);
            String parent = rb.getString("parent").replaceAll("\\.", "/");
            FileUtil.writeUtf8String(data, rb.getString("OutputDir") + "/" + parent + "/" + modelName + "/" + "dto" + "/" + className + "DTO.java");
        }


    }

    //属性
    public static void converNumber(GenDTOColumn column ) {

        if (column.getType().equalsIgnoreCase("number")) {
//            if (column.getRemark().contains("日期") || column.getRemark().contains("时间")) {
//                column.setType("Long");
//            } else {
//                column.setType("Integer");
//            }
            column.setType("Long");
        }

    }

    //获取名称
    private static String getClassName(String fulr) {
        String module_name = fulr.split("/")[3];
        String name = fulr.split("/")[4];
        if (module_name.equalsIgnoreCase("open")) {
            module_name = "";
        }
        return (GenUtil.captureName(module_name) + GenUtil.captureName(name)).replaceAll("\\.", "");
    }
}
